package OnlineExam;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import OnlineExam.*;
import java.util.*;
import OnlineExam.question.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import OnlineExam.db.*;


/**
 *  Handles the evaluation of an explanation given by the user.
 */


public class ExplanationEvaluationAction extends Action
{

	/**
	 *  Action servlet .
	 */

    public ActionForward execute(ActionMapping mapping,ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
	{
	
		HttpSession sess = request.getSession();
		Test test = (Test) sess.getAttribute ("TEST");
		//int len = (Integer)sess.getAttribute ("NUMB");
		Session session = null;	
		int totalMarksScored = 0;
		
		try 
		{
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        	session = sessionFactory.openSession();
			
			List list = test.retrieveGivenAnswers();

			int i =0;
			for (ListIterator iter = list.listIterator(); iter.hasNext();)
			{
				QuestionAnswer qa = (QuestionAnswer) iter.next();
				
				// there exists an explanation and marks are awarded to the explanation.
				//
				if (request.getParameter ("expMarks"+i) != null)
				{	
					int numb = qa.getNumber();
					String hqlUpdate = "update QuestionAnswer set MarksScored = :marksScored, EvaluatorsComment = :evalComm  where TestId = :testId and Number = :numb";
        			int updatedEntities = session.createQuery( hqlUpdate )
                            .setInteger ("marksScored", Integer.parseInt(request.getParameter("expMarks"+i)))
                            .setString ("evalComm",request.getParameter ("evaluatorsComments"+i))
							.setString ("testId", test.getTestId())
							.setInteger ("numb", numb)
                            .executeUpdate();	
					totalMarksScored += Integer.parseInt(request.getParameter("expMarks"+i));
				}
				else
				 	totalMarksScored += qa.getMarksScored();

				i++;
			}
				
			Query query = session.createQuery ("update Test set MarksScored = :marksScored, Evaluated = :evaluated where TestId = :testId");
			query.setInteger ("marksScored", totalMarksScored);
			query.setInteger ("evaluated", 1);
			query.setString ("testId", test.getTestId());
			query.executeUpdate ();			

			return (mapping.findForward ("success"));
		} 
		catch (HibernateException e) 
		{
			System.out.println ("Exception :"+ e);
			return (mapping.findForward ("dbError"));
		}
		finally
		{
			try { if (session != null) session.flush(); session.close (); } 
			catch (Exception e) { System.out.println ("Exception " + e); }
		}

	}
}
